import CodeMirror from "codemirror";

const PLUGIN_NAME = "fullscreen"
const PLUGIN_CMD_NAME: string = PLUGIN_NAME
interface PluginOptions {
  noBind?: boolean
}

type PluginOption = PluginOptions | boolean

interface ExtendedEditorConfiguration extends CodeMirror.EditorConfiguration {
  [PLUGIN_NAME]: PluginOption
}
interface ExtendedEditor extends CodeMirror.Editor {
  getOption<K extends keyof ExtendedEditorConfiguration>(option: K): ExtendedEditorConfiguration[K];
}

const cmdFullscreen = (cm: ExtendedEditor) => {
  const options: PluginOption = cm.getOption(PLUGIN_NAME)
  if (options) {
    const wrapper: HTMLElement = cm.getWrapperElement()
    const parentNode: HTMLElement = wrapper.parentElement
    if (parentNode) {
      parentNode.requestFullscreen()
    } else {
      wrapper.requestFullscreen()
    }
  }
}

const bindKeyMap = (cm: ExtendedEditor) => {
  const keyMaps: CodeMirror.KeyMap = {
    "F11": (cm: CodeMirror.Editor) => {
      cm.execCommand(PLUGIN_CMD_NAME)
    }
  }
  cm.addKeyMap(keyMaps)
}

CodeMirror.defineOption(PLUGIN_NAME, false, function(cm: CodeMirror.Editor, options: PluginOption) {
  if (options) {
    if (options === true || !options.noBind) {
      bindKeyMap(cm as ExtendedEditor)
    }
  }
});

CodeMirror.commands[PLUGIN_CMD_NAME] = cmdFullscreen
